import 'package:flutter/material.dart';
import 'package:flutter_trip_demo/dao/search_dao.dart';
import 'package:flutter_trip_demo/model/search_model.dart';
import 'package:flutter_trip_demo/pages/speaks_page.dart';
import 'package:flutter_trip_demo/utils/navigator/navigator_util.dart';
import 'package:flutter_trip_demo/widght/my_webview.dart';
import 'package:flutter_trip_demo/widght/search_find.dart';

///搜索模块
const TYPE =[
  'channelgroup',
  'gs',
  'plane',
  'train',
  'cruise',
  'district',
  'food',
  'hotel',
  'huodong',
  'shop',
  'sight',
  'ticket',
  'travelgroup'
];

const URLS = 'https://m.ctrip.com/restapi/h5api/globalsearch/search?source=mobileweb&action=mobileweb&keyword=';
class SearchPage extends StatefulWidget {
  final bool? hideLefts;
  final String? searchUrls;
  final String? Keywords;
  final String? hints;


  const SearchPage({Key? key, this.hideLefts,  this.searchUrls = URLS,  this.Keywords,  this.hints}) : super(key: key);

  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  SearchModel? searchModel;
  String? keywords;
  @override
  void initState() {
    if(widget.Keywords!=null){
      _onTextChange(widget.Keywords!);
    }
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          _appBars(),
          MediaQuery.removePadding(
            removeTop: true,
              context: context,
              child:  Expanded(
                flex: 1,
                child: ListView.builder(
                    itemCount: searchModel?.data.length??0,
                    itemBuilder: (BuildContext context,int index){
                      return _items(index);
                    }) )),
              ],
            ),
       );
  }
  _onTextChange(String text){
    keywords = text;
    if(text.length ==0){
      setState(() {
        searchModel =null;
      });
      return;
    }
    String url = widget.searchUrls! + text;
    SearchDio.fetch(url,text).then((SearchModel v){
      if(v.keyword == keywords){
        setState(() {
          searchModel = v;
        });
      }
    }).catchError((e){
      print(e);
    });
  }
  _appBars(){

    return Column(
      children: [
        Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0x66000000),Colors.transparent],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            )
          ),
          child: Container(
            padding: const EdgeInsets.only(top: 20),
            height: 80,
            decoration: const BoxDecoration(color: Colors.white),
            child:  SearchFind(
              hideLeft:widget.hideLefts,
              defaultText:widget.Keywords,
              hint:widget.hints,
              speakClick:_jumpspeak ,
              leftButtonClick:(){
                Navigator.pop(context);
              },
              onChanged:_onTextChange,
            ),
          ),
        )
      ],
    );
  }
  _jumpspeak(){
    NavigatorUtil.push(context, SpeaksPage());
  }
  _items(int index){
    if(searchModel==null||searchModel!.data==null)return null;
    SearchItems items = searchModel!.data[index];
    return GestureDetector(
      onTap: (){
        NavigatorUtil.push(context, MyWebView(url: items.url,title: '详情',));
      },
      child: Container(
        padding: const EdgeInsets.all(10),
        decoration: const BoxDecoration(
          border: Border(
            bottom: BorderSide(width: 0.3,color: Colors.grey))
        ),
        child: Row(
          children: [
            Container(
              margin: const EdgeInsets.all(1),
              child: Image(height: 26,width: 26,image: AssetImage(_typeImg(items.type!)),),
            ),
            Column(
              children: [
                SizedBox(
                  width: 300,
                  child: _maxtitle(items),
                ),
                Container(
                  margin: const EdgeInsets.only(top: 5),
                  width: 300,
                  child: _subtitles(items),
                )
              ],
            )
          ],
        ),

      ),
    );
  }
  _typeImg(String e){
    if(e ==null)return 'images/type_travelgroup.png';
    String p = 'travelgroup';
    for(final val in TYPE){
      if(e.contains(val)){
        p = val;
        break;
      }
    }
    return 'images/type_$p.png';
  }
  _maxtitle(SearchItems items){
    if(items==null){
      return null;
    }
    List<TextSpan> span = [];
    span.addAll(_keySpan(items.word!,searchModel!.keyword!));
    span.add(TextSpan(
        text: ' '+(items.districtname??'')+''+(items.zonename??''),
        style: const TextStyle(fontSize: 16,color: Colors.grey)));
    return RichText(text: TextSpan(children: span));
  }
  _subtitles(SearchItems items){
    return RichText(text: TextSpan(
      children: [
        TextSpan(
          text: items.price??'',
          style: const TextStyle(fontSize: 16,color: Colors.orange),
        ),
        TextSpan(
          text: ' '+(items.star??''),
          style: const TextStyle(fontSize: 12,color: Colors.grey),
        )
      ]
    ));
  }
  _keySpan(String word,String key){
    List<TextSpan> spans = [];
    if(word ==null||word.length==0)return spans;
    String wordLL = word.toLowerCase(), keywordLL = key.toLowerCase();
    List<String> arrs =wordLL.split(keywordLL);
    TextStyle norma = const TextStyle(fontSize: 16,color: Colors.black87);
    TextStyle keynorma = const TextStyle(fontSize: 16,color: Colors.orange);
    int preIndex = 0;
    for(int i=0;i<arrs.length;i++){
     if(i!=0){
       preIndex = wordLL.indexOf(keywordLL,preIndex);
       spans.add(TextSpan(
         text: word.substring(preIndex,preIndex+key.length),
         style: keynorma,
       ));
     }
     String val = arrs[i];
     if(val!=null&&val.length >0){
       spans.add(TextSpan(text: val,style: norma));
     }
    }
    return spans;
  }
}

